package loadbalance;

/**
 * 计算权重
 *
 * @author Daniel
 */
public class WeightUtil {
    private static final int WARMUP = 10;

    public static int getWeight(int weight, int uptime) {
        return getWeight(weight, uptime, WARMUP);
    }

    public static int getWeight(int weight, int uptime, int warmup) {
        if (weight > 0) {
            if (uptime > 0 && uptime < warmup) {
                weight = calculateWarmupWeight(uptime, warmup, weight);
            }
        }
        return weight;
    }

    public static int calculateWarmupWeight(int uptime, int warmup, int weight) {
        // 计算权重，下面代码逻辑上形似于 (uptime / warmup) * weight。
        // 随着服务运行时间 uptime 增大，权重计算值 ww 会慢慢接近配置值 weight
        int ww = (int) ((float) uptime / ((float) warmup / (float) weight));
        return ww < 1 ? 1 : (ww > weight ? weight : ww);
    }

}
